
  angular.module('common',['ui.bootstrap'])
      .service('uiService', ['$rootScope','$modal','$timeout','$q','$sce',function($rootScope, $uibModal, $timeout, $q, $sce){
    var self = this;
     /**
     * 显示错误信息
     * @param  {String} message [错误信息]
     * @param  {String} [type]    []
     * @return {}         []
     */
    var alertPromise;
    this.alert = function(message, type){
      if (type === true) {
        type = 'success';
      }

      //To call Scope.$apply() for the message changing.
      //Without this $timeout(), angularjs won't know the change of the message 
      //if called alert from a directive.
      //Can't call Scope.$apply() directly because when execute in this function,
      //it is alreadyin $apply().
      $timeout(function(){
        $rootScope.alert = {
          type: type,
          msg: message,
        };
      });

      $timeout.cancel(alertPromise);

      alertPromise = $timeout(function() {
        alertPromise = null;
        if ($rootScope.alert.msg == message) {
          $rootScope.alert.msg = '';
        }
      }, 3000);
    };
    /**
     * 弹出层
     * @return {[type]} [description]
     */
    this.modal = function(options){
      options = options || {};
      if(!$rootScope.modal) {
          $rootScope.modal = {};
      }
      //超时promise
      var getTimeoutPromise = function(time){
        var deferred = $q.defer();
        $timeout(function(){
          deferred.reject('timeout ' + time + 's');
        }, time * 1000)
        return deferred.promise;
      }
      $rootScope.modal = angular.extend($rootScope.modal, {
        $templateUrl: options.templateUrl,
        $cancel: function(){
          /*修改
           * liubing
           * 2015/03/02 16:29:17
           * 关闭时清空modal
           */
          $rootScope.modal = {};
          $q.when().then(function () {
            instance.dismiss('cancel')
          });
        },
        $noOkBtn: options.noOkBtn || false,
        $title: options.title,
        $disabled: false,
        //左边按钮内容
        $okText: $sce.trustAsHtml(options.okText || '保存'),
        //点击保存按钮的处理函数
        $ok: function(modalData, modalForm){
          if (!modalForm.$valid) {
            return;
          }
          var okText = modalData.$okText;
          $rootScope.modal.$_okText = okText;
          //禁用保存的按钮
          modalData.$disabled = true;
          modalData.$okText = $sce.trustAsHtml('<span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span>');

          var data = {};
          for(var name in modalData){
            if (name[0] !== '$') {
              data[name] = modalData[name];
            }
          }
          var ret = options.ok(data);

          //$q里没有race方法
          var p1 = $q.when(ret);
          var timeout = getTimeoutPromise(options.timeout || 10);
          var isResolved = false;
          var resolve = function(data){
            instance.dismiss('close');
            $rootScope.modal = {};
            if (data === true) {
              return;
            }
            var successText = options.successText || '保存成功';
            if (typeof data === 'string' && data) {
              successText = data;
            }
            self.alert(successText, true);
          }
          p1.then(function(data){
            if (isResolved) {return};
            isResolved = true;
            //出现错误
            if (data === false) {
              modalData.$disabled = false;
              modalData.$okText = okText;
              return;
            }
            resolve(data);
          }).catch(function(){
            if (isResolved) {return};
            isResolved = true;
            modalData.$disabled = false;
            modalData.$okText = okText;
          });
          timeout.then(function(){
            if (isResolved) {return};
            isResolved = true;
            resolve();
          })
        }
      });
      options.backdrop = "static";
      options.templateUrl = 'modal.html';
      var instance = $uibModal.open(options);
      instance.result.then(function() {
      }, function() {
          $rootScope.modal = {};
      });
      //初始化异步加载
      if (options.load) {
        $rootScope.modal.$disabled = true;
        $rootScope.modalLoading = true;
        var load = options.load();
        $q.when(load).then(function(){
          //新版的bootstrap将不再包涵instance.$scope参数
          $rootScope.modalLoading = false;
        })
      }
      
      return instance;
    };

    this.icons = ['adjust', 'anchor', 'bank', 'cab', 'camera', 'flag', 'info-circle', 'user'];
  }]);
  /**
   * 提示框数据
   */
  angular.module('common').factory('TipService', ['$timeout', function($timeout) {
    return {
      message : null,
      type : null,
      setMessage : function(msg,type){

        this.message = msg;
        this.type = type;

        //提示框显示最多3秒消失
        var _self = this;
        $timeout(function(){
          _self.clear();
        },3000);
      },
      clear : function(){
        this.message = null;
        this.type = null;
      }
    };
  }]);


